package together.news.common.db.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import together.news.common.db.CommonData;
import together.news.common.db.DBHandler;
import together.news.common.db.NewsData;

public class FileDBHandler implements DBHandler<NewsData> {
	
	protected FileHanderHelper fileHelper=new FileHanderHelper();
	
	public  <D extends CommonData> void insert(D data) throws IOException {
		NewsData fileNewsData=(NewsData)data;
		
		File saveFile=fileHelper.maintainDownloadFileSystem(fileNewsData.getNewsGroup(),fileNewsData.getSourceType(),fileNewsData.getSourceURL());
		FileOutputStream stream = new FileOutputStream(saveFile);
		OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
		writer.write(data.getContent());
		writer.flush();
		writer.close();
		
	}

	public String readTemplate(String pageName, String encoding) throws IOException {
		return TogetherFileUtils.read(FileSystemConfig.template_FOLDER+"/"+pageName,encoding);

	}

	public String readPageDataFile(String pageName, String encoding) throws IOException {
		return TogetherFileUtils.read(FileSystemConfig.getMergeFilePath(pageName),encoding);
	}

	public void writerHtmlGenerated(String pageName, String text,String encoding) throws IOException {
		File saveFile=fileHelper.maintainGeneratedFileSystem(pageName);
		TogetherFileUtils.write(saveFile,text,encoding);
	}
	public  void copyTemp2Gen(String sourceFolder) throws IOException{
		File baseFromFolder = new File(FileSystemConfig.template_FOLDER+"/"+sourceFolder);
		File baseToFolder = new File(FileSystemConfig.generate_FOLDER+"/"+sourceFolder);
		if(baseToFolder.exists()==false){
			baseToFolder.mkdirs();
		}
		File[] dataFiles=baseFromFolder.listFiles();
		for(int i=0;dataFiles!=null && i<dataFiles.length;i++){
			File fromFile=dataFiles[i];
			if(fromFile.isDirectory()) continue;
			File toFile=new File(baseToFolder+"/"+fromFile.getName());
			if(toFile.exists()==false){
				toFile.createNewFile();
			}
			FileInputStream fromFileStream = new FileInputStream(fromFile);
			FileOutputStream toFileStream = new FileOutputStream(toFile);
			int buf=fromFileStream.read();
			while(buf!=-1){
				toFileStream.write(buf);
				buf=fromFileStream.read();
			}
			toFileStream.flush();
			toFileStream.close();
			fromFileStream.close();
		}
	}
}
